//
//  HYComfireBookVC.m
//  Booking
//
//  Created by Maybe_文仔 on 2018/9/5.
//  Copyright © 2018年 Duntech. All rights reserved.
//

#import "HYConfirmBookVC.h"
#import "HYBookingSection1Cell.h"
#import "HYBookingSection2Cell.h"
#import "HYMeetingRemarkCell.h"
#import <ContactsUI/ContactsUI.h>
#import "HYSelectInvitersVC.h"
#import "HYBookSuccessView.h"

@interface HYConfirmBookVC ()<UITableViewDelegate,UITableViewDataSource,CNContactPickerDelegate>

@property (nonatomic, strong) UITableView *tableview;
@property (nonatomic, strong) UIButton *confirmBtn;

@property (nonatomic, strong) NSArray *section1TitleArray;
@property (nonatomic, strong) NSMutableArray *section1ContentArray;
@property (nonatomic, strong) NSArray *section1ImgArray;
@property (nonatomic, strong) NSArray *section2ImgArray;
@property (nonatomic, strong) NSArray *section2ContentArray;

@property (nonatomic, copy) NSString *meetingNameStr;
@property (nonatomic, copy) NSString *remarkStr;
@property (nonatomic, copy) NSString *organizationman;
@property (nonatomic, copy) NSString *attendees;
@property (nonatomic, copy) NSString *outattendees;

@end

@implementation HYConfirmBookVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = NSLocalizedString(@"confirmBooking", nil);
    self.view.backgroundColor = KAPP_WHITE_COLOR;
    [self setupSubviews];
    // Do any additional setup after loading the view.
}

-(void)setupSubviews{
    [self.view addSubview:self.tableview];
    [self.view addSubview:self.confirmBtn];
    
    UIView *lineView = [[UIView alloc]init];
    lineView.backgroundColor = RGBColor(178, 178, 178);
    [self.view addSubview:lineView];
    
    [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.right.mas_equalTo(self.view);
        make.height.mas_equalTo(1);
    }];
    [_confirmBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.bottom.equalTo(self.view).offset(-20 * WIDTH_MULTIPLE);
        make.left.equalTo(self.view).offset(20 * WIDTH_MULTIPLE);
        make.height.mas_equalTo(50 * WIDTH_MULTIPLE);
    }];
    
    [_tableview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(lineView.mas_bottom);
        make.left.right.equalTo(self.view);
        make.bottom.equalTo(self.confirmBtn.mas_top);
    }];
}

-(void)confirmBtnAction{
    if (self.meetingNameStr.length == 0) {
        [JRToast showWithText:NSLocalizedString(@"meetingNamePlaceholder", nil)];
        return;
    }
    if (self.organizationman.length == 0) {
        [JRToast showWithText:NSLocalizedString(@"organizerPlaceholder", nil)];
        return;
    }
    if (self.attendees.length == 0) {
        [JRToast showWithText:NSLocalizedString(@"internalPlaceholder", nil)];
        return;
    }
    if (self.outattendees.length == 0) {
        [JRToast showWithText:NSLocalizedString(@"externalPlaceholder", nil)];
        return;
    }
    NSString *startDayTime = [NSString stringWithFormat:@"%@:00",self.startTime];
    NSString *endDayTime = [NSString stringWithFormat:@"%@:00",self.endTime];
    [HYNetRequestHandle bookingMeetingRoomWithCreateBy:[HYUserModel sharedInstance].user.id
                                             attendees:self.attendees
                                            dataSource:@"2"
                                              currdate:self.meetingDate
                                          startDayTime:startDayTime
                                            endDayTime:endDayTime
                                              markName:self.meetingNameStr
                                         meetingroomId:self.roomModel.id
                                       organizationman:self.organizationman
                                          outattendees:self.outattendees
                                                remark:self.remarkStr
                                           Complection:^(BOOL isSuccess) {
                                               
                                               if (isSuccess) {
                                                   
                                                   HYBookSuccessView *bookSuccessView = [[HYBookSuccessView alloc]initwithTitle:NSLocalizedString(@"roomBookedSuccessfully", nil)];
                                                   [bookSuccessView showBookSuccessView];
                                                   bookSuccessView.bookSuccessBlock = ^{
                                                       
                                                       NSArray *pushVCAry = [self.navigationController viewControllers];
                                                       UIViewController *popVC = [pushVCAry objectAtIndex:0];
                                                       [self.navigationController popToViewController:popVC animated:YES];
                                                       //发通知跳到我的预定
                                                       [[NSNotificationCenter defaultCenter] postNotificationName:KBookSussessNotification object:nil];
                                                   };
                                               }
                                               
                                           }];
}

#pragma mark -- UITableViewDataSource
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 3;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 0) {
        return 4;
    }
    else if (section == 1){
        return 3;
    }
    else{
        return 1;
    }
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    kWeakSelf(weakSelf);
    if (indexPath.section == 0) {
        HYBookingSection1Cell *cell = [tableView dequeueReusableCellWithIdentifier:@"HYBookingSection1Cell"];
        [cell setDataWithTitle:self.section1TitleArray[indexPath.row]
                   withContent:self.section1ContentArray[indexPath.row]
                     withImage:self.section1ImgArray[indexPath.row]];
        cell.inputTextChangeBlock = ^(NSString *inputText) {
            weakSelf.meetingNameStr = inputText;
        };
        return cell;
    }
    else if (indexPath.section == 1){
        HYBookingSection2Cell *cell = [tableView dequeueReusableCellWithIdentifier:@"HYBookingSection2Cell"];
        [cell setDataWithImage:self.section2ImgArray[indexPath.row]
                   withContent:self.section2ContentArray[indexPath.row]];
        return cell;
    }
    else{
        HYMeetingRemarkCell *cell = [tableView dequeueReusableCellWithIdentifier:@"HYMeetingRemarkCell"];
        cell.inputTextChangeBlock = ^(NSString *inputText) {
            weakSelf.remarkStr = inputText;
        };
        return cell;
    }
}

#pragma mark -- UITableViewDelegate
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.section == 0) {
        if (indexPath.row == 1 || indexPath.row == 2) {
            HYSelectInvitersVC *selectVC = [HYSelectInvitersVC new];
            if (indexPath.row == 1) {
                selectVC.selectType = HYSelectTypeSingle;
            }
            else{
                selectVC.selectType = HYSelectTypeMultiple;
            }
            [self.navigationController pushViewController:selectVC animated:YES];
            selectVC.selectBlock = ^(NSMutableArray *userIDArray, NSMutableArray *usernameArray) {
                
                NSMutableString *nameStr = [NSMutableString string];
                for (NSInteger i = 0; i < usernameArray.count; i++) {
                    
                    [nameStr appendString:usernameArray[i]];
                    if (i != usernameArray.count - 1) {
                        
                        [nameStr appendString:@","];
                    }
                }
                
                NSMutableString *tempStr = [NSMutableString string];
                for (NSInteger i = 0; i < userIDArray.count; i++) {
                    
                    [tempStr appendString:userIDArray[i]];
                    if (i != userIDArray.count - 1) {
                        [tempStr appendString:@","];
                    }
                }
                if (indexPath.row == 1) {
                    self.organizationman = nameStr;
                }
                else{
                    self.attendees = tempStr;
                }

                [self.section1ContentArray replaceObjectAtIndex:indexPath.row withObject:nameStr];
                [tableView reloadData];
            };
        }
        if (indexPath.row == 3) {
            if (@available(iOS 9.0, *)) {
                CNContactPickerViewController *contactPickerViewController = [[CNContactPickerViewController alloc] init];
                contactPickerViewController.delegate = self;
                [self presentViewController:contactPickerViewController animated:YES completion:nil];
            }
        }
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 2) {
        return 75;
    }
    else{
        return 45;
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section == 0) {
        return 0;
    }
    else{
        return 44;
    }
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UILabel *headView = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, 44)];
    headView.backgroundColor = RGBColor(242, 242, 248);
    headView.font = KFont(15);
    headView.textColor = RGBColor(136, 136, 136);
    if (section == 1) {
        headView.text = [NSString stringWithFormat:@"    %@",NSLocalizedString(@"roomInfo", nil)];
    }
    else if (section == 2){
        headView.text = [NSString stringWithFormat:@"    %@",NSLocalizedString(@"meetingDetail", nil)];
    }
    
    return headView;
}

#pragma mark - contactsDelegate
- (void)contactPicker:(CNContactPickerViewController *)picker didSelectContacts:(NSArray<CNContact *> *)contacts {
    
    // 同时选中多个联系人
    NSMutableString *nameStr = [NSMutableString string];
    for (CNContact *contact in contacts) {
        NSString *givenName = contact.givenName;
        NSString *familyName = contact.familyName;
        NSString *name = [givenName isNotBlank] ? givenName : familyName;
        [nameStr appendString:name];
        [nameStr appendString:@","];
    }

    if (nameStr.length > 0) {
        [self.section1ContentArray replaceObjectAtIndex:3 withObject:[nameStr substringToIndex:nameStr.length-1]];
        self.outattendees = [nameStr substringToIndex:nameStr.length-1];
        [self.tableview reloadData];
    }
    
}

- (void)printContactInfo:(CNContact *)contact {
    
    NSString *givenName = contact.givenName;
    NSString *familyName = contact.familyName;
    NSString *name = [givenName isNotBlank] ? givenName : familyName;
    NSLog(@"givenName=%@, familyName=%@", givenName, familyName);
    NSArray *phoneNumbers = contact.phoneNumbers;
    NSString *phoneNumStr = @"";
    NSString *emailStr = @"";
    NSMutableDictionary *contactDict = [NSMutableDictionary dictionary];
    for (CNLabeledValue <CNPhoneNumber*> *phone in phoneNumbers) {
        
        NSString *label = phone.label;
        CNPhoneNumber *phonNumber = (CNPhoneNumber *)phone.value;
        phoneNumStr = phonNumber.stringValue;
        NSLog(@"label=%@, value=%@", label, phonNumber.stringValue);
    }
    
    for (CNLabeledValue *email in contact.emailAddresses) {
        
        emailStr = email.value;
        DLog(@"email : %@",email);
    }
    [contactDict setValue:name forKey:@"name"];
    [contactDict setValue:phoneNumStr forKey:@"phone"];
    [contactDict setValue:emailStr forKey:@"email"];
//    [self.extennalNameArray addObject:name];
//    [self.extennalAttendeesArray addObject:contactDict];
}

#pragma mark -- 懒加载

-(NSArray *)section1TitleArray{
    if (!_section1TitleArray) {
        _section1TitleArray =  @[NSLocalizedString(@"meetingName", nil),
                                 NSLocalizedString(@"organizer", nil),
                                 NSLocalizedString(@"internalAttendees", nil),
                                 NSLocalizedString(@"externalAttendees", nil)];
    }
    return _section1TitleArray;
}

-(NSMutableArray *)section1ContentArray{
    if (!_section1ContentArray) {
        _section1ContentArray = [NSMutableArray arrayWithArray:@[NSLocalizedString(@"meetingNamePlaceholder", nil),
                                                                 NSLocalizedString(@"organizerPlaceholder", nil),
                                                                 NSLocalizedString(@"internalPlaceholder", nil),
                                                                 NSLocalizedString(@"externalPlaceholder", nil)]];
    }
    return _section1ContentArray;
}

-(NSArray *)section1ImgArray{
    if (!_section1ImgArray) {
        _section1ImgArray = @[@"",@"arrow",@"arrow",@"btn_add"];
    }
    return _section1ImgArray;
}

-(NSArray *)section2ImgArray{
    if (!_section2ImgArray) {
        _section2ImgArray =  @[@"icon_address",@"icon_calendar",@"icon_time"];
    }
    return _section2ImgArray;
}

-(NSArray *)section2ContentArray{
    if (!_section2ContentArray) {
        NSString *meetingTime = [NSString stringWithFormat:@"%@-%@",self.startTime,self.endTime];
        _section2ContentArray = @[self.roomModel.name,self.meetingDate,meetingTime];
    }
    return _section2ContentArray;
}

-(UITableView *)tableview{
    if (!_tableview) {
        _tableview = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        _tableview.backgroundColor = RGBColor(242, 242, 248);
        _tableview.delegate = self;
        _tableview.dataSource = self;
        [_tableview registerClass:[HYBookingSection1Cell class] forCellReuseIdentifier:@"HYBookingSection1Cell"];
        [_tableview registerNib:[UINib nibWithNibName:@"HYBookingSection2Cell" bundle:nil] forCellReuseIdentifier:@"HYBookingSection2Cell"];
        [_tableview registerClass:[HYMeetingRemarkCell class] forCellReuseIdentifier:@"HYMeetingRemarkCell"
         ];
    }
    return _tableview;
}

- (UIButton *)confirmBtn{
    if (!_confirmBtn) {
        _confirmBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_confirmBtn setBackgroundColor:KAPP_THEME_COLOR];
        [_confirmBtn setTitle:NSLocalizedString(@"confirm", nil) forState:UIControlStateNormal];
        [_confirmBtn setTitleColor:KAPP_WHITE_COLOR forState:UIControlStateNormal];
        _confirmBtn.titleLabel.font = KFitFont(16);
        [_confirmBtn addTarget:self action:@selector(confirmBtnAction) forControlEvents:UIControlEventTouchUpInside];
        _confirmBtn.layerCornerRadius = 4;
    }
    return _confirmBtn;
}

-(NSString *)meetingNameStr{
    if (!_meetingNameStr) {
        _meetingNameStr = @"";
    }
    return _meetingNameStr;
}

-(NSString *)organizationman{
    if (!_organizationman) {
        _organizationman = @"";
    }
    return _organizationman;
}

-(NSString *)attendees{
    if (!_attendees) {
        _attendees = @"";
    }
    return _attendees;
}

-(NSString *)outattendees{
    if (!_outattendees) {
        _outattendees = @"";
    }
    return _outattendees;
}

-(NSString *)remarkStr{
    if (!_remarkStr) {
        _remarkStr = @"";
    }
    return _remarkStr;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
